/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/recover-binary-search-tree
   @Language: C++
   @Datetime: 19-03-29 14:55
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	TreeNode *pre=NULL, *p=NULL, *q=NULL;
	void inorder(TreeNode *root){
		if (root==NULL) return;
		if (root->left) inorder(root->left);
		if (pre && pre->val>root->val){
			if (p){
				swap(p->val, root->val);
				pre=p=q=NULL;
				return;
			}
			else {
				p=pre;
				q=root;
			}
		}
		pre=root;
		if (root->right) inorder(root->right);
	}
public:
	/**
	 * @param root: the given tree
	 * @return: the tree after swapping
	 * Tip:
	 * only two node swap
	 * 1) neighbour, swap them
	 * 2) not neighbour, must have (a>b) and (c>d) neighbour, swap (a,d)
	 */
	TreeNode * bstSwappedNode(TreeNode * root) {
		// write your code here
		inorder(root);
		if (p) swap(p->val, q->val);
		return root;
	}
};
